package com.skillworld.webapp.web.pages.rest.tutorial;

import java.util.List;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.tutorial.Tutorial;
import com.skillworld.webapp.model.tutorialservice.TutorialInfo;
import com.skillworld.webapp.model.tutorialservice.TutorialService;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class ViewTutorial 
{    
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @Property
    private TutorialInfo info;
    
    @Property
    private Tutorial tutorial;
    
    @SuppressWarnings("unused")
    @Property
    private long originalId;
    
    @SuppressWarnings("unused")
    @Property
    private List<Tutorial> versions;
    
    @SuppressWarnings("unused")
    @Property
    private Tutorial tut; // loop iterator
        
    @Inject
    private TutorialService tutorialService;
    
    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private Request request;
    
    
    void onPassivate() 
    {
        return;
    }    
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }       
        
        String tutParam = request.getParameter("tut");
        if (tutParam == null)
        {
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }
            
        try 
        { 
            long tutorialId = Long.parseLong(tutParam);
            info = tutorialService.viewTutorial(userSession.getUserId(), tutorialId);
            tutorial = info.getTutorial();
            originalId = (tutorial.isDerived())
                          ? tutorial.getOriginal().getTutorialId()
                          : tutorialId;
            versions = tutorialService.findTutorialVersions(tutorialId);
        } 
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.TUTORIAL_NOT_FOUND; }
    }
}
